package com.by.service.impl;

import com.by.bean.FreighthEnquiry;
import com.by.common.bean.PageBean;
import com.by.common.crud.BaseService;
import com.by.common.crud.BaseServiceImpl;
import com.by.common.utils.AssertUtils;
import com.by.mapper.FreighthEnquiryDetailMapper;
import com.by.mapper.FreighthEnquiryMapper;
import com.by.mapper.FreighthOfferMapper;
import com.by.query.FreightQuery;
import com.by.service.FreighthEnquiryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author Ye QS
 * @version 0.1
 * @className FreighthEnquiryServiceImpl
 * @description
 * @date 2024/9/29 15:55
 * @since jdk11
 */
@Service
public class FreighthEnquiryServiceImpl extends BaseServiceImpl<FreighthEnquiry, FreighthEnquiryMapper> implements FreighthEnquiryService {
    @Autowired
    FreighthEnquiryDetailMapper freighthEnquiryDetailMapper;
    @Autowired
    FreighthOfferMapper freighthOfferMapper;

    /**
     * 保存货代询价单信息
     *
     * @param entity 货代询价单实体对象
     * @return 返回保存操作的结果，1表示成功
     * <p>
     * 该方法实现以下功能：
     * 1. 保存货代询价单基本信息
     * 2. 如果存在关联的明细项，则一并保存
     * 3. 保存能够为该询价单报价的货代信息
     * <p>
     * 使用AssertUtils.isNotSuccess进行错误处理，确保在任何保存步骤失败时抛出异常
     */
    @Override
    public int save(FreighthEnquiry entity) {

        // 保存货代询价单基本信息
        int rs = super.save(entity);
        AssertUtils.isNotSuccess(rs, "保存货代询价单失败");

        // 如果存在关联的明细项，则一并保存
        if (null != entity.getFreighthEnquiryDetailList() && entity.getFreighthEnquiryDetailList().size() > 0) {
            rs = freighthEnquiryDetailMapper.batchSave(entity.getId(), entity.getFreighthEnquiryDetailList());
            AssertUtils.isNotSuccess(rs, "保存货代询价单明细表失败");
        }

        // 保存能够为该询价单报价的货代信息
        rs = freighthOfferMapper.saveFreighth(entity.getId(), entity.getTransportway(), entity.getAirline());
        AssertUtils.isNotSuccess(rs, "保存能够报价的货代失败");

        return 1;
    }

    @Override
    public PageBean queryFreighth(FreightQuery query) {
        PageHelper.startPage(query.getPage(), query.getPageSize());
        List<Map> list = baseMapper.queryFreighth(query);
        PageInfo<Map> mapPageInfo = new PageInfo<>(list);
        return new PageBean(query.getPage(), query.getPageSize(), mapPageInfo.getTotal(), list);
    }
}
